package main

import (
	pb "../customer"
	"context"
	"google.golang.org/grpc"
	"io"
	"log"
)

const (
	address = "localhost:9000"
)

func rpc_CreateCustomer(client pb.CustomerClient, customer *pb.CustomerRequest)  {
	// 本地client调用远程CreateCustomer方法
	resp, err := client.CreateCustomer(context.Background(), customer)
	if err != nil {
		log.Fatal(err)
	}

	if resp.Success {
		log.Println("A new customer has been added with id: ", resp.Id)
	}
}

// 客户端的customer请求，服务端会存储起来， 这样客户端可以通过调用stream api来获取
func rpc_GetCustomers(client pb.CustomerClient, filter *pb.CustomerFilter)  {
	// calling the streaming api
	stream, err := client.GetCustomers(context.Background(), filter)
	if err != nil {
		log.Fatal(err)
	}

	for {
		cus, err := stream.Recv()
		if err == io.EOF {
			break
		}

		if err != nil {
			log.Fatalf("stream recv failed, err: %v", err)
		}
		log.Printf("customer: %v", cus)
	}
}

func main() {
	conn, err := grpc.Dial(address, grpc.WithInsecure())
	if err != nil {
		log.Fatalf("grpc connect failed: %v", err)
	}
	defer conn.Close()

	client := pb.NewCustomerClient(conn)

	customerReq := &pb.CustomerRequest{
		Id: 1,
		Name: "cshi",
		Email: "cshi@qq.com",
		Phone: "110",
		Addresses: []*pb.CustomerRequest_Address {
			&pb.CustomerRequest_Address{
				Street: "weigongcun",
				City: "bj",
				State: "CA",
				Zip: "100",
				IsShippingAddress: false,
			},
			&pb.CustomerRequest_Address{
				Street: "huaruncheng",
				City: "shenzhen",
				State: "nanshan",
				Zip: "200",
				IsShippingAddress: true,
			},
		},
	}

	rpc_CreateCustomer(client, customerReq)

	customerReq = &pb.CustomerRequest{
		Id: 2,
		Name: "cshi2",
		Email: "cshi@qq2.com",
		Phone: "110",
		Addresses: []*pb.CustomerRequest_Address {
			&pb.CustomerRequest_Address{
				Street: "weigongcun",
				City: "bj2",
				State: "CA",
				Zip: "100",
				IsShippingAddress: false,
			},
			&pb.CustomerRequest_Address{
				Street: "huaruncheng",
				City: "shenzhen2",
				State: "nanshan",
				Zip: "200",
				IsShippingAddress: true,
			},
		},
	}
	rpc_CreateCustomer(client, customerReq) // send a second request

	filter := &pb.CustomerFilter{Keyword: ""}
	rpc_GetCustomers(client, filter)
}
